/**
 ** ajax 再封装，为了统一ajax请求
 ** example: var api = require("common/api");
 **   api.request("url",{
 **		 success:function(data){
 **	
 **		 },
 **		 method:'POST',
 **		 error:function(){},
 **		 data:{'name':'text'}	
 **   })
 ** author zhangli
 ** time: 2016-2-24 15:16
**/

define(function(require,exports,module){

	var $ = require('jquery');
	require('./json2');
	//var PropmtBox = require("widgets/propmtbox/propmtbox");

//	window.pendingRequests = window.pendingRequests || {};
//
//	$.ajaxSettings.beforeSend = function(xhr, options) {
//	    var key = options.url,
//	        complete = options.complete,
//	        nothandle = options.nothandle ? true : false,
//	        flag = options.abortOnRetry !== undefined ? !!options.abortOnRetry : true;
//	    if(nothandle){ //不做过滤标示
//	    	return;
//	    }
//	    if (/.+&_=[\d]{13}$/.test(key)) {
//	        key = key.split('&_=')[0];
//	    }
//	    if (!flag) {
//	        return true;
//	    } else {
//	        if (pendingRequests[key] !== undefined) {
//	            return false;
//	        } else {
//	            pendingRequests[key] = xhr;
//	        }
//	        var timer = setTimeout(function() {
//	            timer = null;
//	        }, 5000);
//	        options.complete = function(xhr, Status) { 
//	            delete pendingRequests[key];
//	            if ($.isFunction(complete)) {
//	                complete.apply(this, arguments); 
//	            }
//	        };
//	        return true;
//	    }
//	}

	//全局的ajax访问，处理ajax清求时sesion超时
	$(document).ajaxComplete(function(event,XMLHttpRequest,settings){
	  	//var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus"); // 通过XMLHttpRequest取得响应头，sessionstatus，
　　　　var responseObject = XMLHttpRequest.responseJSON || {};
		if (responseObject && responseObject.code == "0004") {
			//PropmtBox.show(responseObject.message || 'Session已过期，请重新登录',"error")
　　　　　　// 如果超时就处理 ，指定要跳转的页面
　  　　　　//window.location.replace(basePath + "/login");
			var sUserAgent = navigator.userAgent.toLowerCase();
            var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
            var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
            var bIsMidp = sUserAgent.match(/midp/i) == "midp";
            var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
            var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
            var bIsAndroid = sUserAgent.match(/android/i) == "android";
            var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
            var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
            if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
                setTimeout(function(){
					window.location.replace(basePath + "/wx/loginPage");
				},1000);
            } else {
               setTimeout(function(){
					window.location.replace(basePath + "/logout");
				},1000);
            }
			
　　　　}
	});

	//IE8 bind 兼容
	Function.prototype.bind = Function.prototype.bind || function(b) {
	    if (typeof this !== "function") {
	      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
	    }

	    var a = Array.prototype.slice;
	    var f = a.call(arguments, 1);
	    var e = this;
	    var c = function() {};
	    var d = function() {
	      return e.apply(this instanceof c ? this : b || window, f.concat(a.call(arguments)));
	    };

	    c.prototype = this.prototype;
	    d.prototype = new c();

	    return d;
	};

	//IE8 string trim 兼容
	var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
    "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
    "\u2029\uFEFF";
	if (!String.prototype.trim || ws.trim()) {
	    ws = "[" + ws + "]";
	    var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
	        trimEndRegexp = new RegExp(ws + ws + "*$");
	    String.prototype.trim = function trim() {
	        if (this === void 0 || this === null) {
	            throw new TypeError("can't convert "+this+" to object");
	        }
	        return String(this)
	            .replace(trimBeginRegexp, "")
	            .replace(trimEndRegexp, "");
	    };
	}

	//IE8 Array indexOf 兼容
	if (!Array.prototype.indexOf){
	  Array.prototype.indexOf = function(elt /*, from*/){
	    var len = this.length >>> 0;
	    var from = Number(arguments[1]) || 0;
	    from = (from < 0)? Math.ceil(from) : Math.floor(from);
	    if (from < 0){
	      from += len;
	      for (; from < len; from++){
	        if (from in this && this[from] === elt){
	          return from;
	        }
	        return -1;
	      };
	    }
	  }
	}

	function Request(xhr){
		this.xhr = xhr;
		this.alive = true;
	}

	Request.prototype = {
		cancel:function(){
			this.alive = false;
			this.xhr.abort();
		}
	}

	function Client(opitons){
		if(typeof options === "undefined"){
			options = {};
		}
		this.baseUrl = options.baseUrl || '';
		this.activeRequests = {};
	}

	Client.prototype = {
		
		uniqueId:function(){
			function s4(){
				return Math.floor((1 + Math.random()) * 0x10000)
                 .toString(16)
                 .substring(1);
			}
			return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
           		s4() + '-' + s4() + s4() + s4();
		},

		wrapCallback:function(id,func,cleanup){
			if( typeof func === "undefined"){
				return;
			}
			var self = this;
			function wrapped(){
				var req = self.activeRequests[id];
				if(cleanup === true){
					delete self.activeRequests[id];
				}
				if(req.alive){
					return func.apply(req,arguments);
				}
			}
			return wrapped;
		},

		clear:function(){
			for(var id in this.activeRequests){
				this.activeRequests[id].cancel();
			}
		},

		request:function(path,options){
			options = options || {};
			var query = $.param(options.query||'',true);
			var method = options.method || (options.data ? 'POST' : 'POST');
			var data = options.data;
			var id = this.uniqueId();
			var isAsync = options.async === false ? false : true;

			if (typeof data !== 'undefined') {
		      data = JSON.stringify(data);
		    }

		    var fullUrl,
		    	self = this;
		    if (path.indexOf(this.baseUrl) === -1) {
		      fullUrl = this.baseUrl + path;
		    } else {
		      fullUrl = path;
		    }
		    if (query) {
		      if (fullUrl.indexOf('?') !== -1) {
		        fullUrl += '&' + query;
		      } else {
		        fullUrl += '?' + query;
		      }
		    }

		    this.activeRequests[id] = new Request($.ajax({
		      url: fullUrl,
		      method: method,
		      data: data,
		      async : isAsync,
		      contentType: 'application/json',
		      headers: {
		        'Accept': 'application/json; charset=utf-8'
		      },
		      success: self.wrapCallback(id, options.success),
		      error: self.wrapCallback(id, options.error),
		      complete: self.wrapCallback(id, options.complete, true)
		    }));

		    return this.activeRequests[id];

		},
		
		getSLD:function(){
			var domain = document.domain;
			var index = domain.indexOf('.');
			if(index > -1){
				domain = domain.substr(index,domain.length);
			}
			return domain;
		},
		
		getCookie:function getCookie(name)
		{
			var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
			if(arr=document.cookie.match(reg))
				return unescape(arr[2]);
			else
				return null;
		}

	}

	module.exports = new Client();


});